// pages/classHomePage/pk/index/index.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    all_activity_list: [],
    all_pk_list: [],
    people: null,
    items: null,
    card: [{
      title: {
        text: "PK",
        color: "#272635" //字体颜色
      },
      tag: {
        text: "1小时前"
      },
      header: {
        bgcolor: "#f5f5f5",  //#f5f5f5  #fbde35
        line: true
      }
    }],
    funList: {
      'funitems': [{
          "name": "PK",
          "url": "/pages/classHomePage/pk/index/index",
          "pic_url": "/assets/wx_pic/menu_pk@3x.png"
        },
        {
          "name": "盲盒",
          "url": "/pages/classHomePage/blindbox/index/index",
          "pic_url": "/assets/wx_pic/menu_mh@3x.png"
        },
        {
          "name": "签到",
          "url": "/pages/classHomePage/signIn/index/index",
          "pic_url": "/assets/wx_pic/menu_qd@3x.png"
        },
        {
          "name": "辩论会",
          "url": "/pages/classHomePage/debate/index/index",
          "pic_url": "/assets/wx_pic/menu_blh@3x.png"
        },
        {
          "name": "抢答",
          "url": "/pages/classHomePage/qiangda/index/index",
          "pic_url": "/assets/wx_pic/menu_qd_1@3x.png"
        },
        {
          "name": "讨论",
          "url": "/pages/classHomePage/discuss/index/index",
          "pic_url": "/assets/wx_pic/menu_tl@3x.png"
        },
        {
          "name": "成员分组",
          "url": "/pages/classHomePage/group/index/index",
          "pic_url": "/assets/wx_pic/menu_zyfz@3x.png"
        },
        {
          "name": "积分",
          "url": "/pages/classHomePage/integral/index/index",
          "pic_url": "/assets/wx_pic/menu_jf@3x.png"
        },
      ]
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this
    _this.setData({
      people: wx.getStorageSync("people")
    })
    _this.teacher_add_refresh()
    _this.check_student()

  },
  teacher_add_refresh: function () {
    let _this = this
    _this.get_all_activity().then(res_activity => {
      _this.get_all_pk().then(res_pk => {
        // console.log('pk&act:', res_activity, res_pk);
        let new_all_activity_list = []
        for (let index = 0; index < res_pk.length; index++) {
          for (let index2 = 0; index2 < res_activity.length; index2++) {
            if (res_pk[index]['activity_id'] == res_activity[index2]['activity_id']) {
              new_all_activity_list.push(res_activity[index2])
            }
          }
        }
        _this.setData({
          all_activity_list: new_all_activity_list
        })
      })
    })
  },

  gotoPkMessage: function (e) {
    console.log('gotoPkMessage:', e);
    let pk = e.currentTarget.dataset['pk']
    wx.navigateTo({
      url: '/pages/classHomePage/pk/pkMessage/pkMessage?pk=' + JSON.stringify(pk),
    })
  },

  teacher_add_activity: function () {
    let _this = this
    wx.showModal({
      title: '创建pk',
      editable: true, //显示输入框
      placeholderText: '输入活动type', //显示输入框提示信息
      success: res => {
        if (res.confirm) { //点击了确认
          console.log(res.content) //用户输入的值
          let data = {
            'activity_type': res.content,
            'course_name': app.globalData.banji_info['courseName'],
            'teacher_id': app.globalData.teacher_info['id']
          }
          // console.log(data);
          app.formPost('/add_activity_pk?', data).then(res => {
            console.log('创建pk结果：', res);
            _this.get_all_activity().then(res => {
              for (let index = 0; index < res.length; index++) {
                if (data['activity_type'] == res[index]['activity_type']) {
                  let activity_id = res[index]['activity_id']
                  let data_add_pk = {
                    'activity_id': activity_id,
                    'course_name': app.globalData.banji_info['courseName']
                  }
                  app.formPost('/add_pk?', data_add_pk).then(res => {
                    console.log('创建相关activity的pk的结果：', res);
                    _this.teacher_add_refresh()
                  })
                }
              }
            })
          })
        }
      }
    })
  },

  get_all_activity: function () {
    let _this = this
    return new Promise(function (resolve, reject) {
      let data = {}
      if (wx.getStorageSync("people") == 'student') {
        data = {
          'course_name': app.globalData.banji_info['className'],
          'teacher_id': app.globalData.banji_info['teacher_id']
        }
      } else if (wx.getStorageSync("people") == 'teacher') {
        data = {
          'course_name': app.globalData.banji_info['courseName'],
          'teacher_id': app.globalData.banji_info['teacherId']
        }
      }
      app.formPost('/get_all_activity?', data).then(res => {
        console.log('查询activity活动结果/get_all_activity：', res);
        // let title = {}
        // let tag = {}
        // let new_all_activity_list = []
        _this.setData({
          all_activity_list: res
        })

        resolve(res)
      })
    })
  },

  get_all_pk: function () {
    let _this = this
    return new Promise(function (resolve, reject) {
      let data = {}
      if (wx.getStorageSync("people") == 'student') {
        data = {
          'course_name': app.globalData.banji_info['className']
        }
      } else if (wx.getStorageSync("people") == 'teacher') {
        data = {
          'course_name': app.globalData.banji_info['courseName']
        }
      }
      app.formPost('/get_all_pk', data).then(res => {
        console.log('查询PK活动结果/get_all_pk：', res);
        _this.setData({
          all_pk_list: res
        })
        resolve(res)
      })
    })
  },

  teacher_close_pk: function (e) {
    let _this = this
    // console.log(e);
    let activity_id = e.target.dataset['activity_id']
    console.log('activity_id', activity_id);
    console.log('_this.data.all_pk_list', _this.data.all_pk_list);
    let items = null
    for (let index = 0; index < _this.data.all_pk_list.length; index++) {
      if (_this.data.all_pk_list[index]['activity_id'] == activity_id) {
        items = String(_this.data.all_pk_list[index]['stu_item1']) + ',' + String(_this.data.all_pk_list[index]['stu_item2'])
      }

    }
    let data = {
      'activity_id': activity_id,
      'course_name': app.globalData.banji_info['courseName'],
      'items': items
    }
    app.formPost('/close_pk', data).then(res => {
      console.log('关闭pk结果：', res);
    })
  },

  check_student: function () {
    let _this = this
    if (wx.getStorageSync("people") == 'student') {
      let stu_id = app.globalData.student_info['id']
      _this.get_all_pk().then(res => {
        console.log('检查抽中：', res);
        for (let index = 0; index < res.length; index++) {
          if (res[index]['is_finished'] == 0 && (res[index]['student_id_1'] == stu_id || res[index]['student_id_2'] == stu_id)) {
            console.log('你被抽中了！！！！！！！！！:', res);
            let myitem = null
            if (res[index]['student_id_1'] == stu_id) {
              myitem = res[index]['stu_item1']
            } else if (res[index]['student_id_2'] == stu_id) {
              myitem = res[index]['stu_item2']
            }
            let pageList_data = {
              createUser: app.globalData.student_info['id'],
              examPaperId: myitem,
              pageIndex: 1,
              pageSize: 10
            }
            app.formPost('/api/admin/student/exampaper/answer/pageList', pageList_data).then(res2 => {
              console.log('pageList:', res2);
              if (res2['response']['list'].length == 0) {
                wx.navigateTo({
                  url: '/pages/classHomePage/pk/doexam/doexam?activity_id=' + String(res[index]['activity_id'] + '&item=' + String(myitem)),
                })
              }
            })

          }
        }
      })
      // clearInterval(id)
    }
  },

  click_item: function (e) {
    if (e.currentTarget.dataset.url != '') {
      wx.navigateBack()
      wx.navigateTo({
        url: e.currentTarget.dataset.url,
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})